#include "UdpSocket.h"

#define SERVER_PORT 8080        // 服务器端口号,暂定为8888
#define SERVER_IP "172.18.188.222"   // 服务器ip,暂定为本机ip
#define MAX_LISENT_NUM 128      // 最大监听数
#define MAX_BUFFER_SIZE 1024    // 最大缓冲区大小

//socket初始化
void UdpServer::createSocket()
{
    /* 初始化服务 */ 
    m_serverfd = socket(AF_INET, SOCK_STREAM, 0);
    if (m_serverfd = -1)
    {
        perror("socket error");
        exit(EXIT_FAILURE);
    }
    /* 启用端口复用 */ 
    int reuseAddr = 1;
    int ret = setsockopt(m_serverfd, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr));
    if ( ret == -1)
    {
        perror("setsockopt error");
        close(m_serverfd);
    }
}

/* 绑定 */
void UdpServer::bindSocket()
{
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr)); /* 清除脏数据 */

    server_addr.sin_family = AF_INET;   /* 地址族 */
    server_addr.sin_port = htons(m_port); /* 端口需要转成大端 */
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);  /* ip地址需要转成大端 */
    int ret = bind(m_serverfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret == -1)
    {
        perror("bind error");
        exit(EXIT_FAILURE);
    }
}


void UdpServer::acceptConnection()
{
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    char buffer[1024] = {0};
    int client_fd = recvfrom(m_serverfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &client_len);
    if (client_fd == -1) 
    {
        perror("Failed to accept client connection");
        exit(EXIT_FAILURE);
    }

}

void UdpServer::start()
{
    acceptConnection();
}


void UdpClient::connectToServer()
{
    m_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (m_sockfd == -1) 
    {
        perror("Failed to create socket");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(m_serverPort);
    server_addr.sin_addr.s_addr = inet_addr(m_serverIP.c_str());
    #if 0
    int ret = inet_pton(AF_INET, m_serverIP.c_str(), &server_addr.sin_addr);
    if ( ret != 1) 
    {
        perror("Invalid address/ Address not supported");
        exit(EXIT_FAILURE);
    }
    #endif
}
